|
1
|
|
|
import { Inject } from '@nestjs/common'; |
|
2
|
|
|
import { CommandHandler } from '@nestjs/cqrs'; |
|
3
|
|
|
import { SchoolNotFoundException } from 'src/Domain/School/Exception/SchoolNotFoundException'; |
|
4
|
|
|
import { ISchoolRepository } from 'src/Domain/School/Repository/ISchoolRepository'; |
|
5
|
|
|
import { ISchoolUserRepository } from 'src/Domain/School/Repository/ISchoolUserRepository'; |
|
6
|
|
|
import { SchoolUser } from 'src/Domain/School/SchoolUser.entity'; |
|
7
|
|
|
import { UserAlreadyAddedToSchoolException } from 'src/Domain/User/Exception/UserAlreadyAddedToSchoolException'; |
|
8
|
|
|
import { UserNotFoundException } from 'src/Domain/User/Exception/UserNotFoundException'; |
|
9
|
|
|
import { IUserRepository } from 'src/Domain/User/Repository/IUserRepository'; |
|
10
|
|
|
import { IsUserAlreadyAddedToSchool } from 'src/Domain/User/Specification/IsUserAlreadyAddedToSchool'; |
|
11
|
|
|
import { AddUserToSchoolCommand } from './AddUserToSchoolCommand'; |
|
12
|
|
|
|
|
13
|
|
|
@CommandHandler(AddUserToSchoolCommand) |
|
14
|
|
|
export class AddUserToSchoolCommandHandler { |
|
15
|
|
|
constructor( |
|
16
|
|
|
@Inject('ISchoolRepository') |
|
17
|
|
|
private readonly schoolRepository: ISchoolRepository, |
|
18
|
|
|
@Inject('IUserRepository') |
|
19
|
|
|
private readonly userRepository: IUserRepository, |
|
20
|
|
|
@Inject('ISchoolUserRepository') |
|
21
|
|
|
private readonly schoolUserRepository: ISchoolUserRepository, |
|
22
|
|
|
private readonly isUserAlreadyAddedToSchool: IsUserAlreadyAddedToSchool, |
|
23
|
|
|
) {} |
|
24
|
|
|
|
|
25
|
|
|
public async execute(command: AddUserToSchoolCommand): Promise<string> { |
|
26
|
|
|
const { schoolId, userId } = command; |
|
27
|
|
|
|
|
28
|
|
|
const user = await this.userRepository.findOneById(userId); |
|
29
|
|
|
if (!user) { |
|
30
|
|
|
throw new UserNotFoundException(); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
const school = await this.schoolRepository.findOneById(schoolId); |
|
34
|
|
|
if (!school) { |
|
35
|
|
|
throw new SchoolNotFoundException(); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
if (true === (await this.isUserAlreadyAddedToSchool.isSatisfiedBy(school, user))) { |
|
39
|
|
|
throw new UserAlreadyAddedToSchoolException(); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
const schoolUser = await this.schoolUserRepository.save( |
|
43
|
|
|
new SchoolUser(school, user) |
|
44
|
|
|
); |
|
45
|
|
|
|
|
46
|
|
|
// @todo : send email |
|
47
|
|
|
|
|
48
|
|
|
return schoolUser.getId(); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|